package com.ultimatech.webappdemo.authmgr.dao.impl;

import com.ultimatech.webappdemo.authmgr.dao.IAuthDao;
import com.ultimatech.webappdemo.authmgr.vo.GroupVo;
import com.ultimatech.webappdemo.authmgr.vo.PermsVo;
import com.ultimatech.webappdemo.authmgr.vo.RoleVo;
import com.ultimatech.webappdemo.authmgr.vo.UserVo;
import com.ultimatech.webappdemo.base.BaseDao;
import com.ultimatech.webappdemo.base.PageParameter;
import com.ultimatech.webappdemo.base.PageResult;
import com.ultimatech.webappdemo.base.model.*;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.Where;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by 张乐平 on 7/28 0028.
 */
@Component("authDao")
public class AuthDao extends BaseDao implements IAuthDao {
    @Autowired
    public AuthDao(@Qualifier("sessionFactory") SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    public SysUser findByName(String name) {
        Criteria cri = this.getSessionFactory().getCurrentSession().createCriteria(SysUser.class);
        cri.add(Restrictions.eq("username", name));
        List<SysUser> list = cri.list();
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    public List<SysAuthcMap> getAllAuthcMap() {
        Criteria cri = this.getSessionFactory().getCurrentSession().createCriteria(SysAuthcMap.class);
        return cri.list();
    }

    public PageResult<SysUser> getAllUsers(UserVo vo) {
        String hql = "from SysUser as user order by user.createTime desc ";
        Query query = null;
        if (vo != null && vo.getUserName() != null) {
            hql = "from SysUser as user where user.username like :userName order by user.createTime desc ";
            query = this.getSessionFactory().getCurrentSession().createQuery(hql)
                    .setString("userName", "%" + vo.getUserName() + "%");

        } else {
            query = this.getSessionFactory().getCurrentSession().createQuery(hql);
        }
        PageParameter page = this.assemblePageParameter(query, vo.getPager());
        if (page.getPageSize() > 0) {
            query.setMaxResults(page.getPageSize());
            query.setFirstResult(page.getStartIndex());
        }
        List<SysUser> list = query.list();
        vo.setPager(page);
        PageResult<SysUser> result = new PageResult<SysUser>(list, vo.getPager());
        return result;
    }

    public List<SysRole> getAllRoles() {
        String sql = "from SysRole as r order by createTime desc";
        Query query = this.getSessionFactory().getCurrentSession().createQuery(sql);
        return query.list();
    }

    public void saveOrUpdateUser(SysUser user) {
        this.getSessionFactory().getCurrentSession().saveOrUpdate(user);
    }

    public SysRole findRoleByName(String roleName) {
        Criteria cri = this.getSessionFactory().getCurrentSession().createCriteria(SysRole.class);
        cri.add(Restrictions.eq("rolename", roleName));
        List<SysRole> list = cri.list();
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    public SysUser findUserById(Integer userId) {
        return (SysUser) this.getSessionFactory().getCurrentSession().load(SysUser.class, userId);
    }

    public void delUser(SysUser user) {
        this.getSessionFactory().getCurrentSession().delete(user);
    }

    public void updateUser(SysUser user) {
        this.getSessionFactory().getCurrentSession().saveOrUpdate(user);
    }

    public PageResult<SysRole> getAllRoles(RoleVo vo) {
        String hql = "from SysRole as role order by role.createTime desc ";
        Query query = null;
        if (vo != null && vo.getRoleName() != null) {
            hql = "from SysRole as role where role.rolename like :roleName order by role.createTime desc ";
            query = this.getSessionFactory().getCurrentSession().createQuery(hql)
                    .setString("roleName", "%" + vo.getRoleName() + "%");
        } else {
            query = this.getSessionFactory().getCurrentSession().createQuery(hql);
        }
        PageParameter page = this.assemblePageParameter(query, vo.getPager());
        if (page.getPageSize() > 0) {
            query.setMaxResults(page.getPageSize());
            query.setFirstResult(page.getStartIndex());
        }
        List<SysRole> list = query.list();
        vo.setPager(page);
        PageResult<SysRole> result = new PageResult<SysRole>(list, vo.getPager());
        return result;
    }

    public int saveOrUpdateRole(SysRole role) {
        this.getSessionFactory().getCurrentSession().saveOrUpdate(role);
        return role.getId();
    }

    public void saveOrUpdatePermission(SysMyPermission myPermission) {
        this.getSessionFactory().getCurrentSession().saveOrUpdate(myPermission);
    }

    public SysRole findRoleById(Integer roleId) {
        return (SysRole) this.getSessionFactory().getCurrentSession().load(SysRole.class, roleId);
    }

    public boolean RepeatPermission(SysMyPermission myPermission) {
        boolean flag = true;
        String hql = "from SysMyPermission as permission where permission.role.id = :roleId and permission.dataDomain = :dataDomain and permission.dataType = :dataType and permission.operation= :operation ";
        Query query = this.getSessionFactory().getCurrentSession().createQuery(hql)
                .setInteger("roleId", myPermission.getId());
        query.setString("dataDomain", myPermission.getDataDomain());
        query.setString("dataType", myPermission.getDataType());
        query.setString("operation", myPermission.getOperation());
        List<SysMyPermission> permissions = query.list();
        if (permissions != null && permissions.size() > 0) {
            flag = false;
        }
        return flag;
    }

    public void delPermission(SysMyPermission permission) {
        this.getSessionFactory().getCurrentSession().delete(permission);
    }

    public void delRole(SysRole role) {
        this.getSessionFactory().getCurrentSession().delete(role);
    }

    @Override
    public void updatePerms(SysMyPermission myPermission) {

    }

    @Override
    public void delPerms(SysMyPermission myPermission) {

    }

    public PageResult<SysMyPermission> getAllPerm(PermsVo vo) {
        String hql = "from SysMyPermission as role";
        Query query = null;
        if (vo != null && vo.getDataType() != null) {
            hql = "from SysMyPermission as role where role.dataType like :dataType or role.operation like :dataType1 or role.dataDomain like :dataType2";
            query = this.getSessionFactory().getCurrentSession().createQuery(hql)
                    .setString("dataType", "%" + vo.getDataType() + "%").setString("dataType1", "%" + vo.getDataType() + "%").setString("dataType2", "%" + vo.getDataType() + "%");

        } else {
            query = this.getSessionFactory().getCurrentSession().createQuery(hql);
        }
        PageParameter page = this.assemblePageParameter(query, vo.getPager());
        if (page.getPageSize() > 0) {
            query.setMaxResults(page.getPageSize());
            query.setFirstResult(page.getStartIndex());
        }
        List<SysMyPermission> list = query.list();
        vo.setPager(page);
        PageResult<SysMyPermission> result = new PageResult<SysMyPermission>(list, vo.getPager());
        return result;
    }

    @Override
    public SysMyPermission findPermById(Integer roleId) {
        return (SysMyPermission) this.getSessionFactory().getCurrentSession().load(SysMyPermission.class, roleId);
    }

    @Override
    public void delPerm(SysMyPermission id) {
        this.getSessionFactory().getCurrentSession().delete(id);
    }

    @Override
    public void insertGroup(SysGroup group) {
        this.getTemplate().saveOrUpdate(group);
    }

    @Override
    public void saveOrUpdateAuthcMap(SysAuthcMap map) {
        this.getTemplate().saveOrUpdate(map);
    }

    @Override
    public PageResult<SysGroup> getAllGroups(GroupVo vo) {
        String where = "where name like :name and moduleName like :moduleName";
        String hql = "from SysGroup as group " + where + " order by group.createTime desc ";
        Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
        if (vo != null && vo.getName() != null) {
            query.setParameter("name", "%" + vo.getName() + "%");

        } else {
            query.setParameter("name", "%%");
        }
        if (vo != null && vo.getModuleName() != null) {
            query.setParameter("moduleName", "%" + vo.getModuleName() + "%");

        } else {
            query.setParameter("moduleName", "%%");
        }
        PageParameter page = this.assemblePageParameter(query, vo.getPager());
        if (page.getPageSize() > 0) {
            query.setMaxResults(page.getPageSize());
            query.setFirstResult(page.getStartIndex());
        }
        List<SysGroup> list = query.list();
        vo.setPager(page);
        PageResult<SysGroup> result = new PageResult<SysGroup>(list, vo.getPager());
        return result;
    }

    @Override
    public void saveOrUpdateObj(Object obj) {
        this.getTemplate().saveOrUpdate(obj);
    }

    @Override
    public SysGroup getGroupByName(String name) {
        List list = this.getTemplate().find("from SysGroup where name=?", name);
        return list != null && list.size() > 0 ? (SysGroup) list.get(0) : null;
    }
}
